from typing import Optional
from ultralytics import YOLOWorld

# 加载模型
model = YOLOWorld("static/model/best_model.pt")

def detect_objects(image_path: str) -> Optional[str]:
    """
    检测图像中的对象，并返回置信度最高的物品名称

    参数：
    image_path (str): 输入图像的路径

    返回：
    Optional[str]: 置信度最高的物品名称，如果没有检测到物品则返回 None
    """
    try:
        # 执行图像推理
        results = model.predict(source=image_path, save=False)

        # 初始化最高置信度和对应类别
        max_confidence = -1
        best_object = None

        for result in results:
            if result.boxes and result.boxes.conf is not None:
                # 获取类别索引和置信度
                classes = result.boxes.cls.cpu().numpy().astype(int)
                confidences = result.boxes.conf.cpu().numpy()

                # 找到最高置信度的类别
                max_index = confidences.argmax()
                if confidences[max_index] > max_confidence:
                    max_confidence = confidences[max_index]
                    best_object = model.names[classes[max_index]]

        return best_object if best_object else None

    except Exception as e:
        print(f"检测出错：{str(e)}")
        return None